package com.emellend.api.list;

import java.util.ArrayList;

import com.emellend.api.R;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class List8 extends ListActivity {
	private PhotoAdapter mAdapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_8);
		//当list列表为空时显示
		getListView().setEmptyView(findViewById(R.id.empty));
		mAdapter=new PhotoAdapter(this);
		setListAdapter(mAdapter);
		
		findViewById(R.id.add).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mAdapter.addPhotos();
			}
		});
		findViewById(R.id.clear).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mAdapter.clearPhotos();
			}
		});
	}
	
	private class PhotoAdapter extends BaseAdapter{
		 private Integer[] mPhotoPool = {
	                R.drawable.sample_thumb_0, R.drawable.sample_thumb_1, R.drawable.sample_thumb_2,
	                R.drawable.sample_thumb_3, R.drawable.sample_thumb_4, R.drawable.sample_thumb_5,
	                R.drawable.sample_thumb_6, R.drawable.sample_thumb_7};
		private ArrayList<Integer> mPhotos=new ArrayList<Integer>();
		private Context mContext;
		
		public PhotoAdapter(Context context){
			mContext=context;
		}
		
		public int getCount() {
			return mPhotos.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public void clearPhotos() {
			mPhotos.clear();
			notifyDataSetChanged();
		}
		
		public void addPhotos() {
			int whichPhoto=(int) Math.round(Math.random()*(mPhotoPool.length-1));
			int newPhoto=mPhotoPool[whichPhoto];
			mPhotos.add(newPhoto);
			notifyDataSetChanged();
		}
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView;
			if (convertView==null) {
				imageView=new ImageView(mContext);
				imageView.setAdjustViewBounds(true);
				imageView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
						ViewGroup.LayoutParams.WRAP_CONTENT));
				imageView.setBackgroundResource(R.drawable.picture_frame);
			} else {
				imageView=(ImageView) convertView;
			}
			imageView.setImageResource(mPhotos.get(position));
			return imageView;
		}
		
	}
}
